import os
import time
import numpy as np

def convert(txt):  # size:(原图w,原图h) , box:(xmin,xmax,ymin,ymax)
    dw = 1./640     # 1/w
    dh = 1./640     # 1/h
    x = (txt[0] + txt[2])/2.0   # 物体在图中的中心点x坐标
    y = (txt[1] + txt[3])/2.0   # 物体在图中的中心点y坐标
    w = txt[2] - txt[0]         # 物体实际像素宽度
    h = txt[3] - txt[1]         # 物体实际像素高度
    x = x*dw    # 物体中心点x的坐标比(相当于 x/原图w)
    w = w*dw    # 物体宽度的宽度比(相当于 w/原图w)
    y = y*dh    # 物体中心点y的坐标比(相当于 y/原图h)
    h = h*dh    # 物体宽度的宽度比(相当于 h/原图h)
    return (x, y, w, h)    # 返回 相对于原图的物体中心点的x坐标比,y坐标比,宽度比,高度比,取值范围[0-1]

if __name__ == '__main__':
    t = time.time()
    print('Transfer .txt to .xml...ing....')
    txt_folder = 'E:/DATA/PCBDatasets/txt'
    news_txt_folder = 'E:/DATA/PCBDatasets/news_txt'
    txt_file = os.listdir(txt_folder)


    for txt in txt_file:
        new_txts = []
        txt_full_path = os.path.join(txt_folder, txt)
        a = np.loadtxt(txt_full_path)
        news_txt_full_path = os.path.join(news_txt_folder, txt)
        print(news_txt_full_path)
        for ii in a:
            new_txt = convert(ii)
            print(new_txt)
            with open(news_txt_full_path, 'a') as f:
                f.write(str(int(ii[4])) + " " + " ".join([str(a) for a in new_txt]) + '\n')

    print("Transfer .txt to .XML sucessed. costed: {:.3f}s...".format(time.time() - t))